package bma.common.langutil.jmshell.jvm;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import bma.common.langutil.concurrent.BMAThreadPoolExecutor;
import bma.common.langutil.concurrent.ThreadPoolSquare;
import bma.common.langutil.core.ObjectPair;
import bma.common.langutil.core.StringUtil;
import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;
import bma.common.langutil.jmshell.command.AbstractSimpleCommandProcessor;

public class JVMThreadPoolSetCommand extends AbstractSimpleCommandProcessor {

	public JVMThreadPoolSetCommand() {
		super("threadpoolset");
		setArgsTips("[threadPoolName]");
	}

	@Override
	public CommandOptionParser createCommandOption(Session session) {
		CommandOptionParser r = new CommandOptionParser();
		r.addIntegerOption('m', "maxsize", "set threadpool max size");
		r.addIntegerOption('t', "keeplivetime",
				"set threadpool keeplive time, in seconds");
		r.addIntegerOption('c', "coresize", "set threadpool core size");
		return r;
	}

	@Override
	public boolean processCommand(Session s, String cmd,
			CommandOptionParser options) {
		int m = options.getOptionValue("maxsize", new Integer(-1));
		int t = options.getOptionValue("keeplivetime", new Integer(-1));
		int c = options.getOptionValue("coresize", new Integer(-1));
		String[] args = options.getRemainingArgs();
		if ((m != -1 || t != -1 || c != -1) && args != null && args.length > 0) {
			String name = args[0];
			set(s, name, c, m, t);
			return true;
		}
		s.writeln(getHelp(s));
		return true;
	}

	public void set(Session s, String name, int c, int m, int t) {
		List<ObjectPair<String, Object>> tplist = ThreadPoolSquare.list();
		for (ObjectPair<String, Object> op : tplist) {
			if (StringUtil.equals(name, op.getValue())) {
				Object threadPool = op.getAttribute();
				if (threadPool instanceof BMAThreadPoolExecutor) {
					BMAThreadPoolExecutor ex = (BMAThreadPoolExecutor) threadPool;
					if (c > 0) {
						ex.setCorePoolSize(c);
					}
					if (m > 0) {
						ex.setMaximumPoolSize(m);
					}
					if (t > 0) {
						ex.setKeepAliveTime((long) t, TimeUnit.SECONDS);
					}
				} else if (threadPool instanceof ThreadPoolExecutor) {
					ThreadPoolExecutor ex = (ThreadPoolExecutor) threadPool;
					if (c > 0) {
						ex.setCorePoolSize(c);
					}
					if (m > 0) {
						ex.setMaximumPoolSize(m);
					}
					if (t > 0) {
						ex.setKeepAliveTime((long) t, TimeUnit.SECONDS);
					}
				}
				s.writeln("threadpool set done");
				return;
			}
		}

		s.writeln("[ERROR] '" + name + "' not found");
	}
}